package com.jeesite.modules.ic.api;

import com.alibaba.fastjson.JSONObject;
import com.icecold.utils.HtmlUtil;
import com.jeesite.common.codec.Md5Utils;
import com.jeesite.common.config.Global;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.image.ImageUtils;
import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.XmlMapper;
import com.jeesite.modules.component.CatchService;
import com.jeesite.modules.config.Result;
import com.jeesite.modules.ic.dao.IcCardDao;
import com.jeesite.modules.ic.dao.IcUserDao;
import com.jeesite.modules.ic.entity.IcUser;
import com.jeesite.modules.ic.service.IcUserService;
import com.jeesite.modules.ic.service.wx.FileService;
import com.jeesite.modules.ic.service.wx.WxApiService;
import com.jeesite.modules.rt.dao.RtAskDao;
import com.jeesite.modules.rt.entity.RtAsk;
import com.jeesite.modules.rt.entity.RtBanner;
import com.jeesite.modules.rt.entity.RtVersion;
import com.jeesite.modules.rt.entity.RtXieyi;
import com.jeesite.modules.rt.service.RtAskService;
import com.jeesite.modules.rt.service.RtBannerService;
import com.jeesite.modules.rt.service.RtVersionService;
import com.jeesite.modules.utils.SMS.SMSUtil;
import com.jeesite.modules.utils.SMS.Sample;
import com.jeesite.modules.utils.wx.WxMini;
import com.jeesite.modules.utils.wx.vo.WxTuisong;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("/app")
@RestController
@Slf4j
@CrossOrigin
public class AppLoginController {

    @Autowired
    private IcUserService icUserService;

    @Autowired
    private WxMini wxMini;

    @Autowired
    private CatchService catchService;
    @Autowired
    private WxApiService wxApiService;
    @Autowired
    private IcUserDao icUserDao;
    @Autowired
    private RtVersionService rtVersionService;
    @Autowired
    private RtAskDao rtAskDao;
    @Autowired
    private FileService fileService;
    @Autowired
    private IcCardDao icCardDao;
    @Autowired
    private RtAskService rtAskService;
    @Autowired
    private RtBannerService rtBannerService;

    @Value("${self.baseUrl}")
    private String selfBaseUrl;

    @Autowired
    RestTemplate restTemplate;

    /**
     * 常见问题详情
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/login/bannerList")
    public Result bannerList(HttpServletRequest request, HttpServletResponse response){
        List<RtBanner> list = rtBannerService.findList(new RtBanner());
        for (RtBanner rtAsk : list){
            rtAsk.setPic(selfBaseUrl+rtAsk.getPic());
            String content = rtAsk.getContent();
            content = HtmlUtil.repairContent(content,selfBaseUrl);
            rtAsk.setContent(content);
        }
        return Result.buildSuccessResult(list);
    }

    /**
     * 常见问题详情
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/login/bannerInfo")
    public Result bannerInfo(String id,HttpServletRequest request, HttpServletResponse response){
        RtBanner rtBanner = rtBannerService.get(id);
        String content = rtBanner.getContent();
        content = HtmlUtil.repairContent(content,selfBaseUrl);
        rtBanner.setContent(content);
        return Result.buildSuccessResult(rtBanner);
    }

    /**
     * 常见问题详情
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/login/rtAskInfo")
    public Result rtAskInfo(RtAsk rtAsk, HttpServletRequest request, HttpServletResponse response){
        rtAsk = rtAskService.get(rtAsk);
        String content = rtAsk.getContent();
        content = HtmlUtil.repairContent(content,selfBaseUrl);
        rtAsk.setContent(content);
        return Result.buildSuccessResult(rtAsk);
    }


    /**
     * 假数据
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("login/jiashuju")
    public Result jiashuju(HttpServletRequest request, HttpServletResponse response){
        String canyuNum = Global.getConfig("canyu_num");
        long count = icUserService.findCount(new IcUser());
        List<Map<String, Object>> listJia = icCardDao.getListJia();
        Map<String, Object> map = new HashMap<>();
        map.put("canyuNum", Long.valueOf(canyuNum)+count);
        map.put("listJia", listJia);
        return Result.buildSuccessResult(map);
    }

    /**
     * 隐私协议
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("login/rtXieyi")
    public Result rtXieyi(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        if(StringUtils.isEmpty(id)){
            id = "1";
        }
        RtXieyi xieyiById = rtAskDao.getXieyiById(id);
        return Result.buildSuccessResult(xieyiById);
    }


    /**
     * 获取应用版本
     */
    @RequestMapping("login/getVersion")
    public Result getVersion(RtVersion rtVersion){
        List<RtVersion> list = rtVersionService.findList(rtVersion);
        return Result.buildSuccessResult(list.get(0));
    }

    /**
     * 获取应用版本插件版本
     */
    @RequestMapping("login/getVersionChajian")
    public Result getVersionChajian(HttpServletRequest request,HttpServletResponse response){
        String versionOld = request.getParameter("versionName");//应用当前版本名称（已自动获取）
        String type = request.getParameter("type");//平台（1101是安卓，1102是IOS）
        RtVersion rtVersionSearch = new RtVersion();
        rtVersionSearch.setType("1101".equals(type)?1L:2L);
        rtVersionSearch.setName("帮帮兼职");
        List<RtVersion> list = rtVersionService.findList(rtVersionSearch);
        for (RtVersion rtVersion : list) {
            Map<String,Object> map = new HashMap<>();
            map.put("versionCode",rtVersion.getVersion());
            map.put("versionName",rtVersion.getName());
            map.put("versionInfo",rtVersion.getShuoming());
            map.put("updateType",rtVersion.getIsQingzhi()==1?"forcibly":"solicit");
            map.put("downloadUrl",rtVersion.getUrl());
            String version = rtVersion.getVersion();
            String[] splitNew = version.split("\\.");
            String[] splitOld = versionOld.split("\\.");
            if(Integer.valueOf(splitNew[0]) < Integer.valueOf(splitOld[0])){
                return Result.buildSuccessResult();
            }else{
                if(Integer.valueOf(splitOld[0]) == Integer.valueOf(splitOld[0])){
                    if(Integer.valueOf(splitNew[1]) < Integer.valueOf(splitOld[1])){
                        return Result.buildSuccessResult();
                    }else{
                        if(Integer.valueOf(splitNew[1]) == Integer.valueOf(splitOld[1])){
                            if(Integer.valueOf(splitNew[2]) <= Integer.valueOf(splitOld[2])){
                                return Result.buildSuccessResult();
                            }
                        }
                    }
                }
                return Result.buildSuccessResult(map);
            }
        }
        return Result.buildSuccessResult();
    }

    /**
     * 手机号绑定（验证码验证）
     * @param icUser1
     * @return
     */
    @RequestMapping("login/loginByCodeBind")
    public Result loginByCodeBind(IcUser icUser1){
        String mobile = icUser1.getMobile();
        String code = icUser1.getCode();
        String wxLoginId = icUser1.getId();
        icUser1 = icUserService.get(icUser1);
        String appWxOpenid = icUser1.getAppWxOpenid();
        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(code)){
            return Result.buildFailureResult("请输入正确的手机号或验证码");
        }
        Object smscode = catchService.getHashCache("SMSCODE", mobile);
        if(smscode!=null){
            String codeR = (String) smscode;
            log.info("缓存的验证码:"+codeR);
            if(codeR.equals(code)){

                //判断手机号是否存在
                IcUser icUser = icUserService.getOneUserByMobile(mobile);
                if(icUser!=null){
                    if(StringUtils.isNotEmpty(icUser.getAppWxOpenid())){
                        return Result.buildFailureResult("当前手机号已绑定");
                    }else{
                        //手机号未绑定微信号，则绑定手机号
                        icUser.setAppWxOpenid(appWxOpenid);
                        icUser.setParentUserId(icUser1.getParentUserId());
                        icUserService.save(icUser);
                        icUser1 = icUserService.login(icUser);
                        //删除微信openid创建的账号
                        icUserDao.deleteUser(wxLoginId);
                    }
                }else{
                    //新用户
                    icUser1.setMobile(mobile);
                    icUser1 = icUserService.loginNew(icUser1);
                }
                return Result.buildSuccessResult(icUser1);
            }else{
                return Result.buildFailureResult("验证码错误");
            }
        }else{
            return Result.buildFailureResult("验证码不存在或已过期,请重新发送");
        }
    }

    /**
     * App微信登录
     */
    @RequestMapping("appLoginGetWxUserInfo")
    public Result appLoginGetWxUserInfo(HttpServletRequest request, HttpServletResponse response){
        String code = request.getParameter("code");
        String parentId = request.getParameter("parentId");
        //获取openId和accesstoken
        String appAccessToken = wxApiService.getAppAccessToken(code);
        JSONObject jsonObject = JSONObject.parseObject(appAccessToken);
        String access_token = jsonObject.getString("access_token");
        if(StringUtils.isNotEmpty(access_token)){
            String openid = jsonObject.getString("openid");
             IcUser icUser = icUserService.getByAppWxOpenId(openid);
            if(icUser==null){
                icUser = new IcUser();
            }
            icUser.setAppWxOpenid(openid);
            icUser.setAccessToken(access_token);
            if(StringUtils.isNotEmpty(parentId)){
                icUser.setParentUserId(parentId);
            }

            icUser = icUserService.loginNew(icUser);
            return Result.buildSuccessResult(icUser);
        }else{
            log.error("微信登录返回："+jsonObject);
            return Result.buildFailureResult("微信登录失败");
        }

    }



    /**
     * 公众号事件推送
     * @return
     */
    @RequestMapping("wxPush")
    public String wxPush(HttpServletRequest request, HttpServletResponse response){
        String echostr = request.getParameter("echostr");
        // 获取请求体的输入流
        try {
            ServletInputStream inputStream = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuilder xmlStringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                xmlStringBuilder.append(line);
            }
            // 此时xmlStringBuilder.toString()包含了完整的XML数据
            String xmlData = xmlStringBuilder.toString();
            log.info("关注公众号："+xmlData);
            Map<String, Object> stringObjectMap = WxTuisong.xmlParser(xmlData, "xml");
            log.info("关注公众号OPENID："+stringObjectMap.get("->xml->FromUserName"));
            String openId = stringObjectMap.get("->xml->FromUserName").toString();
            String unionId = wxMini.getUnionIdGongzhong(openId);
            if(StringUtils.isNotEmpty(unionId)){
                IcUser icUser = new IcUser();
                icUser.setUnionid(unionId);
                IcUser oneUser = icUserService.getOneUser(icUser);
                if(oneUser!=null){
                    oneUser.setWxOpenid(openId);
                    icUserService.save(oneUser);
                }else{
                    catchService.addHashCache("gongzhonghao_unionId",unionId,openId);
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return echostr;
    }



    /**
     * 头像
     * @param icUser
     * @return
     */
    @RequestMapping("saveAvatarUrlNicheng")
    public Result saveAvatarUrlNicheng(IcUser icUser){
        String avatarUrl = icUser.getAvatarUrl();
        String nicheng = icUser.getNicheng();

        String lineUrl = fileService.onLinePicSaveServer(avatarUrl);
        icUser = icUserService.get(icUser);
        icUser.setAvatarUrl(lineUrl);
        icUser.setNicheng(nicheng);
        icUserService.save(icUser);

        return Result.buildSuccessResult();
    }

    /**
     * 小程序手机号登录
     * @param icUser
     * @return
     */
    @RequestMapping("login")
    public Result login(IcUser icUser){
        String accessToken = wxMini.getAccessToken();
        String mobile = wxMini.getMobile(icUser.getCode(),accessToken);
        JSONObject jsonObject = JSONObject.parseObject(mobile);
        int errcode = jsonObject.getIntValue("errcode");
        if(errcode==0){
            JSONObject phone_info = jsonObject.getJSONObject("phone_info");
            String phoneNumber = phone_info.getString("phoneNumber");
            icUser.setMobile(phoneNumber);
        }
        icUser = icUserService.loginNew(icUser);
        return Result.buildSuccessResult(icUser);
    }



    /**
     * 小程序登录
     * @param icUser
     * @return
     */
    @RequestMapping("login/getOpenId")
    public Result getOpenId(IcUser icUser){
        String openId = wxMini.getOpenId(icUser.getCode());
        JSONObject jsonObject = JSONObject.parseObject(openId);
        String unionid = null;
        if (jsonObject.getIntValue("errcode")==0){
            openId = jsonObject.getString("openid");
            unionid = jsonObject.getString("unionid");
        }else{
            return Result.buildFailureResult("获取OPENID失败");
        }
        icUser = icUserService.get(icUser);
        icUser.setOpenid(openId);
        if(unionid!=null){
            icUser.setUnionid(unionid);
            Object gongzhonghaoUnionId = catchService.getHashCache("gongzhonghao_unionId", unionid);
            if(gongzhonghaoUnionId!=null){
                icUser.setWxOpenid(gongzhonghaoUnionId.toString());
                catchService.delHashCache("gongzhonghao_unionId", unionid);
            }
        }
        icUserService.save(icUser);
        return Result.buildSuccessResult(icUser);
    }



    /**
     * 发送验证码
     * @param icUser
     * @return
     */
    @RequestMapping("login/sendCode")
    public Result sendCode(IcUser icUser){
        String mobile = icUser.getMobile();
        if(StringUtils.isEmpty(mobile)){
            return Result.buildFailureResult("请输入正确的手机号");
        }


        Object smscodetime = catchService.getHashCache("SMSCODETIME", mobile);
        int sendCount = 0;
        if(smscodetime!=null){
            String count = (String) smscodetime;
            sendCount = Integer.valueOf(count).intValue();
            if(sendCount>=10){
                return Result.buildFailureResult("您24小时内发送验证码过多，请24小时后再试");
            }
        }
        String randomNum = StringUtils.getRandomNum(4);
        log.info("RANDOMNUM:"+randomNum);

        //todo 发送验证码
        String code = Sample.sendSMS(mobile, randomNum);
//        String code = sendTmpMsm(mobile, randomNum);
        if("OK".equals(code)){
            catchService.addHashCache("SMSCODE",mobile,randomNum,5,TimeUnit.MINUTES);
            catchService.addHashCache("SMSCODETIME",mobile,sendCount+++"",24,TimeUnit.HOURS);
            return Result.buildSuccessResult("验证码已发送");
        }else{
            return Result.buildFailureResult("验证码发送失败，请稍后再试");
        }

    }

    /**
     * 临时验证码
     * @param mobile
     * @param code
     * @return
     */
    public String sendTmpMsm(String mobile,String code){
        String url = String.format("http://v.juhe.cn/sms/send?key=%s&tpl_id=%s&tpl_value=%s&mobile=%s",
                "a2bcacf3f87324bee09b9f1364717d29","266571","#code#="+code,mobile);
        System.out.println(url);
//        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("key","a2bcacf3f87324bee09b9f1364717d29");
        postParameters.add("tpl_id","266571");
        postParameters.add("tpl_value","#code#="+code);
        postParameters.add("mobile",mobile);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(postParameters, httpHeaders);
        String result = restTemplate.postForObject("http://v.juhe.cn/sms/send", httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        int errcode = jsonObject.getIntValue("error_code");
        System.out.println(result);
        if(errcode==0){
            return "OK";
        }else{
            return "FALSE";
        }
    }


    /**
     * 验证码登录
     * @param icUser
     * @return
     */
    @RequestMapping("login/loginByCode")
    public Result loginByCode(IcUser icUser){
        String mobile = icUser.getMobile();
        String code = icUser.getCode();

        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(code)){
            return Result.buildFailureResult("请输入正确的手机号或验证码");
        }
        if("ceshilihanbing".equals(code)){
            icUser = icUserService.login(icUser);
            return Result.buildSuccessResult(icUser);
        }
        Object smscode = catchService.getHashCache("SMSCODE", mobile);
        if(smscode!=null){
            String codeR = (String) smscode;
            log.info("缓存的验证码:"+codeR);
            if(codeR.equals(code)){

                icUser = icUserService.login(icUser);
                return Result.buildSuccessResult(icUser);

            }else{
                return Result.buildFailureResult("验证码错误");
            }
        }else{
            return Result.buildFailureResult("验证码不存在或已过期,请重新发送");
        }

    }

    /**
     * 手机号一键登录
     * @param icUser
     * @return
     */
    @RequestMapping("login/loginByMobile")
    public Result loginByMobile(IcUser icUser){
        String mobile = icUser.getMobile();

        if(StringUtils.isEmpty(mobile) && mobile.length()==11){
            return Result.buildFailureResult("请输入正确的手机号或验证码");
        }
        icUser = icUserService.login(icUser);
        return Result.buildSuccessResult(icUser);
    }



}
